<template>
  <div>
    <van-nav-bar title="升级VIP" fixed>
      <img
        src="~assets/image/arrow_left.png"
        alt=""
        slot="left"
        width="20"
        height="20"
        @click="leftClick"
      />
    </van-nav-bar>
    <div class="xx"></div>

    <div class="count-top">
      <div
        class="count-img"
        v-for="(item, index) in displayImgList"
        :key="'a' + index"
      >
        <img
          :src="require('assets/image/update_item' + item.grade + '.png')"
          width="25"
          height="25"
          alt=""
        />
        <div
          class="count-img-height"
          :style="{ height: 20 * (1 + index) + 'px' }"
        />
        <div class="count_zhi" v-if="grade == item.grade">
          <img
            src="~assets/image/upgrade_btn_hand.png"
            width="20"
            height="20"
            alt=""
          />
        </div>
        <div class="count_zhi" v-else></div>
        <div class="count-img-text">{{ item.gradeName }}</div>
      </div>
    </div>

    <!-- -->
    <div
      class="item"
      v-for="(item, index) in displayWayList"
      :key="'b' + index"
      :style="{
        backgroundImage: 'url(' + itembg(item) + ')',
      }"
    >
      <div class="item-top">
        <p class="item-top-left"></p>
        <p class="item-top-name">{{ item.name }}</p>
        <img
          :src="require('assets/image/update_item' + item.grade + '.png')"
          alt=""
          width="30"
          height="35"
        />
      </div>
      <div class="item-main">
        <div class="item-main-left">
          <p>产品收益说明：</p>
          <p>{{ item.earningsState }}</p>
        </div>
        <p class="item-main-right" v-if="getHideMoney(item)">
          {{ item.upgradestate }}
        </p>
        <p class="item-main-right" v-else>
          {{ item.money | getMoney }}
        </p>
      </div>
      <div class="item-footer">
        <div @click="selectFineBe(item)">
          查看细则
          <img
            src="~assets/image/icon_updateright.png"
            width="10"
            height="10"
            alt=""
          />
        </div>
        <div
          :class="{
            'item-footer-update':
              grade >= item.grade
                ? false
                : item.trueFalseBuy == 1 || item.trueFalseBuy == 3
                ? false
                : true,
          }"
          @click="updateClick(item)"
        >
          {{
            grade >= item.grade
              ? "已经升级"
              : item.trueFalseBuy == 1 || item.trueFalseBuy == 3
              ? "联系客服"
              : "一键升级"
          }}
        </div>
      </div>
    </div>
    <van-popup
      v-model="showup"
      position="bottom"
      round
      :safe-area-inset-bottom="true"
      :style="{ height: '40%' }"
    >
      <p>选择支付方式</p>

      <div
        class="popup"
        v-for="(item, index) in RechargeWayList"
        :key="'c' + index"
        @click="popupClick(item)"
      >
        <img :src="item.log" width="30" height="30" alt="" />
        <div class="up">
          <div class="up-name">{{ item.name }}</div>

          <div>{{ item.remarks }}</div>
        </div>
        <div v-if="item.name == '余额购买'" class="up-tui">
          {{
            account.balance >= tuiJina
              ? "推荐使用," + account.balance + "元"
              : "余额不足, " + account.balance + "元"
          }}
        </div>
        <img src="~assets/image/arr_rigth.png" width="9" height="15" alt="" />
      </div>
    </van-popup>

    <van-popup
      v-model="moneyShow"
      position="bottom"
      round
      :safe-area-inset-bottom="true"
      :style="{ height: '58%' }"
    >
      <p>请输入支付密码</p>
      <van-password-input
        :value="moneyPwd"
        info="密码为 6 位数字"
        :error-info="errorInfo"
        :gutter="10"
        :length="6"
        focused
        @focus="showKeyboard = true"
      />
      <!-- 数字键盘 -->
      <van-number-keyboard
        v-model="moneyPwd"
        :show="showKeyboard"
        @input="onInput"
        @blur="showKeyboard = true"
      />
    </van-popup>
  </div>
</template>
<script>
import {
  queryAllProductsApi,
  queryUserInfoApi,
  queryOemInfoApi,
  queryRechargeWayApi,
  queryBuyProductionUrlByYiLianApi,
  queryAccountInfoApi,
  queryPayPasswordInfoApi,
} from "network/ApiServe";

export default {
  name: "ProductUpgrade",
  filters: {
    getMoney(money) {
      return "￥" + parseFloat(money).toFixed(2);
    },
  },
  created() {
    this.brandId = localStorage.getItem("brandId");
    this.token = localStorage.getItem("token");
    this.userId = localStorage.getItem("userId");
    this.phone = localStorage.getItem("phone");
  },
  data() {
    return {
      oemInfo: {},
      displayWay: [
        { type: "0", text: "线上购买显示价格" },
        { type: "1", text: "线下客服显示价格" },
        { type: "2", text: "线上购买不显示价格" },
        { type: "3", text: "线下客服不显示价格" },
        { type: "4", text: "前端不展示产品" },
      ],

      displayWayList: [],
      grade: 0,
      displayImgList: [],
      showup: false,
      RechargeWayList: [],

      moneyShow: false,
      moneyPwd: "",
      showKeyboard: true,
      account: {},
      tuiJina: 0,
      updateItem: {},
      subChannelTag: "",

      errorInfo: "",
    };
  },
  // watch: {
  //   moneyPwd(value) {
  //     if (value.length === 6) {
  //       queryPayPasswordInfoApi(this.token, value)
  //         .then((res) => {
  //           console.log("getPayPasswordInfo", res);
  //           if (res.resp_code === "000000") {
  //             this.errorInfo = "正在請求中。。。";

  //             // this.getMoneyPurchase(
  //             //   this.updateItem.money,
  //             //   this.updateItem.name,
  //             //   this.subChannelTag,
  //             //   this.updateItem.id
  //             // );
  //             console.log("queryPayPasswordInfoApi:", res);
  //           }
  //         })
  //         .catch((err) => {
  //           console.log(err);
  //         });
  //     } else {
  //       this.errorInfo = "";
  //     }
  //   },
  // },
  mounted() {
    this.getAllProducts();
    this.getUserInfo();
    this.getOemInfo();
    this.getqRechargeWay();
    this.getAccount();
  },
  methods: {
    leftClick() {
      this.$router.back(-1);
    },
    // 网络请求 升级数据
    getAllProducts() {
      queryAllProductsApi(this.brandId)
        .then((res) => {
          this.displayWayList = [];
          this.displayImgList = [];
          console.log("queryAllProductsApi:", res);
          if (res.resp_code === "000000") {
            res.result.filter((item, i) => {
              let userGrade = {};
              if (item.trueFalseBuy != this.displayWay[4].type) {
                this.displayWayList.push(item);
                userGrade.grade = item.grade;
                userGrade.gradeName = item.name;
                this.displayImgList.push(userGrade);
              }
            });
          }
          let user = { grade: 0, gradeName: "普通用户" };
          this.displayImgList.push(user);
          this.displayWayList = this.displayWayList.reverse();
          this.displayImgList = this.displayImgList.reverse();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getOemInfo() {
      queryOemInfoApi(this.brandId)
        .then((res) => {
          console.log("res:", res);
          if (res.resp_code === "000000") {
            this.oemInfo = res.result;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getUserInfo() {
      this.grade = 0;
      queryUserInfoApi(this.token)
        .then((res) => {
          if ((res.resp_code = "000000")) {
            this.grade = parseInt(res.result.grade);
            console.log("getUserInfo:", this.grade);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getqRechargeWay() {
      this.RechargeWayList = [];
      queryRechargeWayApi(this.userId)
        .then((res) => {
          if (res.resp_code === "000000") {
            res.result.filter((item) => {
              // this.RechargeWayList.push(item);
              if (item.channelNo == "6") {
                this.RechargeWayList.push(item);
              } else if (item.channelNo == "7") {
                this.RechargeWayList.push(item);
              } else if (item.channelNo == "8") {
                this.RechargeWayList.push(item);
              }
            });
            console.log("this.RechargeWayList:", this.RechargeWayList);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 是否显示价格
    getHideMoney(item) {
      let flag = false;
      switch (item.trueFalseBuy) {
        case this.displayWay[0].type:
        case this.displayWay[1].type:
          flag = false;
          break;
        case this.displayWay[2].type:
        case this.displayWay[3].type:
          flag = true;
          break;
      }
      return flag;
    },
    //背景
    itembg(item) {
      let bg;
      switch (parseInt(item.grade)) {
        case 1:
        case 6:
          bg = require("assets/image/img_yqc_upgrade_card_1.png");
          break;
        case 2:
        case 7:
          bg = require("assets/image/img_yqc_upgrade_card_2.png");
          break;
        case 3:
        case 8:
          bg = require("assets/image/img_yqc_upgrade_card_3.png");
          break;
        case 4:
        case 9:
          bg = require("assets/image/img_yqc_upgrade_card_4.png");
          break;
        case 5:
        default:
          bg = require("assets/image/img_yqc_upgrade_card_5.png");
          break;
      }

      return bg;
    },

    // 查看细则
    selectFineBe(item) {
      this.$router.push({
        name: "ProductDetail",
        params: {
          gradeName: item.name,
          grade: item.grade,
          id: item.id,
        },
      });
    },
    // updateClick
    updateClick(item) {
      let _this = this;
      if (_this.grade >= parseInt(item.grade)) {
        //
        _this.$dialog
          .alert({
            title: "立即升级",
            message: "你已经购买过该产品,无需再次购买!",
          })
          .then(() => {});
      } else {
        switch (item.trueFalseBuy) {
          case this.displayWay[1].type:
          case this.displayWay[3].type:
            // _this.$toast("联系客服!");
            _this.$dialog
              .confirm({ title: "立即升级", message: "该产品需要联系客服人员" })
              .then(() => {
                window.location.href = "tel:" + _this.oemInfo.brandPhone;
              })
              .catch(() => {});
            break;
          case this.displayWay[0].type:
          case this.displayWay[2].type:
            _this.$dialog
              .confirm({
                title: "立即升级",
                message:
                  "尊敬的会员：\n        您即将购买《" +
                  item.name +
                  "》产品，如您以后想购买更高等级的产品，则需重新购买，无法补差价哦！" +
                  "【升级之前请先仔细阅读产品费率详情说明】",
              })
              .then(() => {
                this.showup = true;
                this.tuiJina = item.money;
                this.updateItem = item;
              })
              .catch(() => {});
            break;
        }
      }
    },
    //支付
    popupClick(item) {
      let _this = this;
      console.log("支付", item.name);
      this.showup = false;
      this.subChannelTag = item.subChannelTag;
      if (item.name == "余额购买") {
        if (_this.account.balance >= _this.tuiJina) {
          _this.moneyShow = true;
          console.log("_this.tuiJina:", _this.tuiJina);
        } else {
          _this.$dialog
            .alert({
              title: "充值结果",
              message: "余额不足",
            })
            .then(() => {
              // on close
            });
        }
      } else {
        _this.$dialog
          .alert({
            title: "充值结果",
            message: "正在开发中...",
          })
          .then(() => {
            // on close
          });
      }
    },
    //查询账户信息接口
    getAccount() {
      queryAccountInfoApi(this.token)
        .then((res) => {
          if (res.resp_code == "000000") {
            this.account = res.result;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    //校验支付密码接口
    getPayPasswordInfo(password) {
      queryPayPasswordInfoApi(this.token, password)
        .then((res) => {
          console.log("getPayPasswordInfo", res);

          if (res.resp_code === "000000") {
            this.errorInfo = "正在校验支付密码,请稍等...";
            // this.moneyShow = false;

            this.getMoneyPurchase(
              this.updateItem.money,
              this.updateItem.name,
              this.subChannelTag,
              this.updateItem.id
            );
          } else {
            this.moneyPwd = "";
            this.errorInfo = res.resp_message;
            this.moneyShow = true;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //余额购买
    getMoneyPurchase(money, name, subChannelTag, productId) {
      queryBuyProductionUrlByYiLianApi(
        this.brandId,
        this.phone,
        money,
        name,
        subChannelTag,
        productId,
        "",
        ""
      )
        .then((res) => {
          console.log("余额购买", res);
          this.moneyPwd = "";
          this.moneyShow = false;
          // this.errorInfo = res.resp_message;
          this.$dialog
            .alert({
              title: "充值结果",
              message: res.resp_message,
            })
            .then(() => {
              // on close
            });

          if (res.resp_code === "000000") {
            this.getAllProducts();
            this.getUserInfo();
            this.getqRechargeWay();
          }
          this.errorInfo = "密码为 6 位数字";
        })
        .catch((err) => {
          console.log("1111111", err);
        });
    },
    //輸入
    onInput(key) {
      this.moneyPwd = (this.moneyPwd + key).slice(0, 6);
      if (this.moneyPwd.length == 6) {
        this.getPayPasswordInfo(this.moneyPwd);
      }
    },
  },
};
</script>
<style scoped>
.xx {
  margin-top: 47px;
}
.count-top {
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  background-color: #fff;
  padding: 10px 15px;
  align-items: flex-end;
  text-align: center;
}
.count-img {
  font-size: 14px;
}

.count-img-height {
  margin-top: 12px;
  padding-left: 10px;
  padding-right: 10px;
  height: 20px;
  width: 30px;
  background-image: linear-gradient(#ffb633, #fe7c2e);
}
.count-img-text {
  width: 30px;
  height: 40px;
  font-size: 12px;
}
.count_zhi {
  height: 20px;
  margin-top: 5px;
  margin-bottom: 5px;
}

.item {
  margin: 5px;
  padding: 2px 0px 5px 10px;
  /* background-image: url(" ~assets/image/img_upgrade_item1.png"); */
  background-repeat: no-repeat;
  background-size: 100%;
  color: #fff;
}
.item-top {
  display: flex;
  justify-content: space-between;
  text-align: center;
  font-size: 16px;
}
.item-top-left {
  width: 40px;
}
.item-top-name {
  margin-top: 10px;
  text-align: center;
}
.item-main {
  display: flex;
  justify-content: space-between;
}

.item-main-left {
  flex: 4;
  margin-right: 10px;
  font-size: 14px;
}
.item-main-left p {
  line-height: 20px;
  letter-spacing: 1.2px;
}
.item-main-right {
  flex: 2;
  margin-right: 10px;
  font-size: 16px;
  padding-top: 10px;
}
.item-footer {
  margin-top: 20px;
  margin-bottom: 20px;
  margin-right: 5px;
  display: flex;
  flex-direction: row-reverse;
}
.item-footer div {
  margin-right: 8px;
  background-color: #fff;
  color: #999999;
  border-radius: 15px;
  font-size: 14px;
  padding: 5px 10px;
}
div.item-footer-update {
  background-color: #d6ffb0;
  color: #444;
}

.count_zhi img {
  transition: all 0.3s ease;
}
.van-popup {
  background-color: #efefef;
}
.van-popup p {
  margin-top: 10px;
  padding-bottom: 10px;
  text-align: center;
  font-size: 16px;
  font-weight: 600;
  color: #444;
  border-bottom: 1px solid #ccc;
}
.popup {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 15px;
  border-bottom: 1px solid #ccc;
}
.up {
  flex: 1;
  font-size: 12px;
  margin-left: 10px;
  color: #444;
}
.up-name {
  font-size: 16px;
  margin-bottom: 5px;
}

.van-password-input {
  margin-top: 20px;
}
.up-tui {
  margin-right: 15px;
  color: #ff976a;
  font-size: 15px;
}
</style>